#!/usr/bin/env python
# -*- coding:utf-8 -*-
from django.template import Library
from django.urls import reverse
from django.http import QueryDict
from django.conf import settings


def advanced_reverse(request, name, **kwargs):
    """
    反向生成带原始条件的URL
    :param request:
    :param name:
    :param kwargs:
    :return:
    """
    _filter = request.GET.get(settings.BACK_FILTER_KEY)
    base_url = reverse(name, **kwargs)
    if not _filter:
        return base_url
    return "%s?%s" % (base_url, _filter)


def advanced_url(request, name, **kwargs):
    """
    反向生成含条件的URL
    :param request: 请求相关所有数据
    :param name: 反向生成URL的别名
    :param kwargs: 参数
    :return:
    """
    base_url = reverse(name, kwargs=kwargs)
    if not request.GET:
        return base_url

    query_dict = QueryDict(mutable=True)
    query_dict[settings.BACK_FILTER_KEY] = request.GET.urlencode()

    return "%s?%s" % (base_url, query_dict.urlencode())


def advanced_origin_params(request, name, **kwargs):
    """
    生成和原条件相同的URL
    :param request:
    :param name:
    :param kwargs:
    :return:
    """
    base_url = reverse(name, kwargs=kwargs)
    if not request.GET:
        return base_url

    return "%s?%s" % (base_url, request.GET.urlencode())
